/**
 * 文档格式化工具
 */

export interface DocumentFormat {
  h1Style: string;
  h2Style: string;
  bodyStyle: string;
  containerStyle: string;
}

// 标准格式配置
export const STANDARD_FORMAT: DocumentFormat = {
  // 一级标题：黑体三号，段前段后空1行，左对齐
  h1Style: `
    font-family: 'SimHei', '黑体', sans-serif;
    font-size: 16pt;
    font-weight: bold;
    text-align: left;
    margin-top: 1em;
    margin-bottom: 1em;
    line-height: 1.5;
  `,
  
  // 二级标题：黑体四号，段前段后空0.5行，左对齐
  h2Style: `
    font-family: 'SimHei', '黑体', sans-serif;
    font-size: 14pt;
    font-weight: bold;
    text-align: left;
    margin-top: 0.5em;
    margin-bottom: 0.5em;
    line-height: 1.5;
  `,
  
  // 正文：仿宋GB-2312小四号，两端对齐，首行缩进两个字符
  bodyStyle: `
    font-family: 'FangSong_GB2312', '仿宋_GB2312', '仿宋', serif;
    font-size: 12pt;
    text-align: justify;
    text-indent: 2em;
    line-height: 1.5;
    margin-bottom: 0.5em;
  `,
  
  // 容器样式
  containerStyle: `
    max-width: 800px;
    margin: 0 auto;
    padding: 40px;
    background: white;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
  `
};

/**
 * 格式化Markdown内容为标准格式HTML
 */
export function formatContentToStandardHTML(content: string, title?: string): string {
  // 处理Markdown格式
  let formattedContent = content;
  
  // 处理一级标题
  formattedContent = formattedContent.replace(
    /^# (.+)$/gm,
    `<h1 style="${STANDARD_FORMAT.h1Style.replace(/\s+/g, ' ').trim()}">$1</h1>`
  );
  
  // 处理二级标题
  formattedContent = formattedContent.replace(
    /^## (.+)$/gm,
    `<h2 style="${STANDARD_FORMAT.h2Style.replace(/\s+/g, ' ').trim()}">$2</h2>`
  );
  
  // 处理三级标题（按二级标题格式）
  formattedContent = formattedContent.replace(
    /^### (.+)$/gm,
    `<h2 style="${STANDARD_FORMAT.h2Style.replace(/\s+/g, ' ').trim()}">$1</h2>`
  );
  
  // 处理段落
  const paragraphs = formattedContent.split('\n\n');
  const formattedParagraphs = paragraphs.map(paragraph => {
    const trimmed = paragraph.trim();
    if (!trimmed) return '';
    
    // 跳过已经是HTML标签的内容
    if (trimmed.startsWith('<h1') || trimmed.startsWith('<h2')) {
      return trimmed;
    }
    
    // 处理列表
    if (trimmed.includes('\n- ') || trimmed.includes('\n1. ')) {
      return formatList(trimmed);
    }
    
    // 普通段落
    return `<p style="${STANDARD_FORMAT.bodyStyle.replace(/\s+/g, ' ').trim()}">${trimmed}</p>`;
  });
  
  // 生成完整HTML
  const fullHTML = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title || '文档'}</title>
    <style>
        @page {
            margin: 2.54cm;
        }
        body {
            margin: 0;
            padding: 0;
            font-family: 'FangSong_GB2312', '仿宋_GB2312', '仿宋', serif;
        }
        .document-container {
            ${STANDARD_FORMAT.containerStyle.replace(/\s+/g, ' ').trim()}
        }
        .document-title {
            ${STANDARD_FORMAT.h1Style.replace(/\s+/g, ' ').trim()}
            text-align: center;
            margin-bottom: 2em;
        }
    </style>
</head>
<body>
    <div class="document-container">
        ${title ? `<h1 class="document-title">${title}</h1>` : ''}
        ${formattedParagraphs.join('\n')}
    </div>
</body>
</html>`;
  
  return fullHTML;
}

/**
 * 格式化列表
 */
function formatList(content: string): string {
  const lines = content.split('\n');
  let listHTML = '';
  let inList = false;
  let listType = '';
  
  for (const line of lines) {
    const trimmed = line.trim();
    
    if (trimmed.startsWith('- ')) {
      if (!inList || listType !== 'ul') {
        if (inList) listHTML += `</${listType}>`;
        listHTML += '<ul>';
        inList = true;
        listType = 'ul';
      }
      listHTML += `<li style="margin-bottom: 0.25em;">${trimmed.substring(2)}</li>`;
    } else if (/^\d+\.\s/.test(trimmed)) {
      if (!inList || listType !== 'ol') {
        if (inList) listHTML += `</${listType}>`;
        listHTML += '<ol>';
        inList = true;
        listType = 'ol';
      }
      listHTML += `<li style="margin-bottom: 0.25em;">${trimmed.replace(/^\d+\.\s/, '')}</li>`;
    } else if (trimmed && inList) {
      listHTML += `</${listType}>`;
      inList = false;
      if (trimmed) {
        listHTML += `<p style="${STANDARD_FORMAT.bodyStyle.replace(/\s+/g, ' ').trim()}">${trimmed}</p>`;
      }
    } else if (trimmed) {
      listHTML += `<p style="${STANDARD_FORMAT.bodyStyle.replace(/\s+/g, ' ').trim()}">${trimmed}</p>`;
    }
  }
  
  if (inList) {
    listHTML += `</${listType}>`;
  }
  
  return listHTML;
}

/**
 * 预览格式化效果
 */
export function previewFormattedContent(content: string, title?: string): string {
  return formatContentToStandardHTML(content, title);
}
